package lnkwe.sys.ueditor;



import com.lnkwe.sys.ueditor.define.ActionMap;
import com.lnkwe.sys.ueditor.define.AppInfo;
import com.lnkwe.sys.ueditor.define.BaseState;
import com.lnkwe.sys.ueditor.define.State;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * Created by lijing on 2016-03-25.
 */
public class UEditorAction {
    private HttpServletRequest request = null;
    private String rootPath = null;
    private String contextPath = null;
    private String actionType = null;
    private ConfigManager configManager = null;
    public UEditorAction ( HttpServletRequest request ) {

        this.request = request;
        this.rootPath=request.getSession().getServletContext().getRealPath("/");
        this.actionType = request.getParameter( "action" );
        this.contextPath = request.getContextPath();

    }
    public String exec() {
       /* this.actionType = request.getParameter("action");
        this.contextPath = request.getContextPath();
        this.rootPath = request.getSession().getServletContext().getRealPath("/");
        this.configManager = ConfigManager.getInstance(this.rootPath, this.contextPath, request.getRequestURI());*/
        String callbackName = this.request.getParameter("callback");

        if (callbackName != null) {

            if (!validCallbackName(callbackName)) {
                return new BaseState(false, AppInfo.ILLEGAL).toJSONString();
            }

            return callbackName + "(" + this.invoke() + ");";

        } else {
            return this.invoke();
        }

    }

    public String invoke() {

        if (actionType == null || !ActionMap.mapping.containsKey(actionType)) {
            return new BaseState(false, AppInfo.INVALID_ACTION).toJSONString();
        }


        State state = null;

        int actionCode = ActionMap.getType(this.actionType);

        Map<String, Object> conf = null;

        switch (actionCode) {

            case ActionMap.CONFIG:
                System.out.println("xxx:");
                return this.configManager.getAllConfig().toString();

            case ActionMap.UPLOAD_IMAGE:
            case ActionMap.UPLOAD_SCRAWL:
            case ActionMap.UPLOAD_VIDEO:
            case ActionMap.UPLOAD_FILE:

                break;

            case ActionMap.CATCH_IMAGE:

                break;

            case ActionMap.LIST_IMAGE:
            case ActionMap.LIST_FILE:

                break;

        }

        return state.toJSONString();

    }

    public int getStartIndex() {

       String start = this.request.getParameter("start");

        try {
            return Integer.parseInt(start);
        } catch (Exception e) {
            return 0;
        }

    }

    /**
     * callback参数验证
     */
    public boolean validCallbackName(String name) {

        if (name.matches("^[a-zA-Z_]+[\\w0-9_]*$")) {
            return true;
        }

        return false;

    }

}
